package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.dao.UserMapper;
import com.example.demo.model.User;
import com.example.demo.service.UserFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 功能描述：
 *
 * @Author: Zhanghf
 * @Date: 2021/5/20 17:20
 */

@RequestMapping("login")
@Controller
public class LoginController {
    @Autowired(required = false)
    private UserMapper userMapper;
    @Resource
    private UserFeignService userFeignService;
    @RequestMapping(value = "loginpage", method = {RequestMethod.GET, RequestMethod.POST})
    public String login(HttpServletResponse response, HttpServletRequest request, Model model) {
        return "login";
    }
    //先只实现用户名密码登录
    @PostMapping("checking")
    public String checking(HttpServletResponse response, HttpServletRequest request, Model model, HttpSession session) {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        boolean checking = userFeignService.checklogin(username, password);
        if (!checking) {
            model.addAttribute("tips", "用户名密码不正确，请重新登录");
            return "login";
        } else {
            User user = userMapper.selectOne(new QueryWrapper<User>().eq("name", username));
            session.setAttribute("user", user);
            //出现的问题
            //没有在控制类中有打印语句，结果控制台没有输出，以为是什么问题
            //原因是  return "index"; 直接转发到html页面
            //要把请求转发到controller 要forward:index;   直接写index，请求转发到了/login/index
            //结果404，没有错误提示信息 无可用消息  ，改成 forward:/index;有效果  提示信息405  Request method 'POST' not supported
            //原因 从Post请求checking转发到index，index 支持 Get请求，不支持post请求
            //重定向代表一次新的请求；请求转发没有发起新请求，
            //所有进行请求转发
            // return "forward:index";
//            登录后跳转回原来的界面，怎么实现
//            return "forward:"+request.getParameter("url");
            return "redirect:/index";
        }

    }

    @GetMapping("out")
    public String out(HttpServletResponse response, HttpServletRequest request, Model model, HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/index";
    }
}
